<script setup>
import { ref, onBeforeMount } from 'vue'
import { Edit, Delete } from '@element-plus/icons-vue'
import {
  userPagesService,
  userAddService,
  userUpdateService,
  userDeleteMultipleService
} from '@/api/user'

// 查询条件表单数据
const formInline = ref({
  currentPage: 1,
  pageSize: 10,
  name: '',
  sex: '',
  phone: '',
  carNumber: '',
  limitation: '',
  startTime: '',
  endTime: ''
})

// 条件查询表单对象
const queryForm = ref()

const loading = ref(false)

// 用户信息表格数据
const tableData = ref()

// 定义分页条参数
const pages = ref({
  total: 0
})

// 获取表格数据
const getUserPages = async () => {
  loading.value = true
  const res = await userPagesService(formInline.value)
  pages.value = res.data
  tableData.value = pages.value.records
  loading.value = false
}

// 组件挂载前加载数据
onBeforeMount(async () => {
  formInline.value.currentPage = 1
  formInline.value.pageSize = 10
  await getUserPages()
})

// 多选处理
const multipleSelection = ref()

const handleSelectionChange = (rows) => {
  multipleSelection.value = rows

  // TODO 切换页后，之前选中的数据将丢失
}

const onSizeChange = (size) => {
  //每页条数变化了，重新从第一页渲染即可
  formInline.value.currentPage = 1
  formInline.value.pageSize = size
  getUserPages()
}

const onCurrentChange = (pagenum) => {
  // 更新当前页
  formInline.value.currentPage = pagenum
  getUserPages()
}

// 修改、增加弹窗
const dialogVisible = ref(false)

// 修改、增加表单数据
const formModel = ref({
  id: '',
  name: '',
  sex: '',
  phone: '',
  carNumber: ''
})

// 修改、增加表单对象
const dialogForm = ref()

// 表单规则
const queryRules = {
  name: [{ pattern: /^[^\d]*$/, message: '名字格式错误', trigger: 'blur' }],
  phone: [
    { pattern: /^\d{1,11}$/, message: '手机号格式错误', trigger: 'blur' }
  ],
  carNumber: [
    {
      pattern: /^\S{1,9}$/,
      message: '车牌号格式错误',
      trigger: 'blur'
    }
  ]
}

const editRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { pattern: /^[^\d]*$/, message: '名字格式错误', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }
  ],
  sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
  carNumber: [
    {
      pattern: /^\S{7,9}$/,
      message: '车牌号格式错误',
      trigger: 'blur'
    }
  ]
}

// 查询表单校验后提交
const getUserQuery = async () => {
  await queryForm.value.validate()
  getUserPages()
}

// 添加逻辑
const onAddUser = () => {
  formModel.value = {}
  dialogVisible.value = true
}

//编辑逻辑
const onEditUser = (row) => {
  formModel.value = { ...row }
  dialogVisible.value = true
}

const onSubmit = async () => {
  await dialogForm.value.validate()
  if (formModel.value.id) {
    await userUpdateService(formModel.value)
  } else {
    await userAddService(formModel.value)
  }

  ElMessage.success(formModel.value.id ? '编辑成功' : '添加成功')
  // 弹层关闭
  dialogVisible.value = false
  // 重新渲染
  getUserPages()
}

const onDeleteUser = async (row) => {
  await ElMessageBox.confirm('你确认删除该用户吗？', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })

  await userDeleteMultipleService(row.id).then(() => {
    ElMessage.success({ type: '', message: '删除成功' })
    getUserPages()
  })
}

const onDeleteUsers = async () => {
  const tips = multipleSelection.value.map(
    (row) => '<i>' + row.name + ' : ' + row.carNumber + '</i><br />'
  )
  const ids = multipleSelection.value.map((row) => row.id)
  await ElMessageBox.confirm(
    '你确认删除<br/>' + tips.join('') + '吗？',
    '温馨提示',
    {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      dangerouslyUseHTMLString: true
    }
  )
  await userDeleteMultipleService(ids)
  ElMessage({ type: 'success', message: '删除成功' })
  getUserPages()
}
</script>

<template>
  <div class="root">
    <el-container class="list">
      <el-header>
        <el-form
          :inline="true"
          :model="formInline"
          :rules="queryRules"
          ref="queryForm"
        >
          <el-form-item label="姓名" prop="name" style="width: 200px">
            <el-input
              v-model="formInline.name"
              placeholder="请输入要查询的姓名"
              clearable
            />
          </el-form-item>

          <el-form-item label="性别">
            <el-select
              v-model="formInline.sex"
              placeholder="请选择要查询的性别"
              clearable
              style="width: 180px"
            >
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="formInline.phone"
              placeholder="请输入要查询的手机号"
              clearable
              style="width: 170px"
            />
          </el-form-item>

          <el-form-item label="车牌号" prop="carNumber">
            <el-input
              v-model="formInline.carNumber"
              placeholder="请输入要查询的车牌号"
              clearable
              style="width: 170px"
            />
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
              v-model="formInline.startTime"
              placeholder="开始时间"
              type="date"
              format="YYYY-MM-DD"
              value-format="x"
              clearable
              style="width: 140px"
            />
            &nbsp;&nbsp;--&nbsp;&nbsp;
            <el-date-picker
              v-model="formInline.endTime"
              type="date"
              placeholder="结束时间"
              format="YYYY-MM-DD"
              value-format="x"
              clearable
              style="width: 140px"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="getUserQuery">查询</el-button>

            <el-button type="primary" @click="onAddUser"> 添加用户 </el-button>

            <el-button type="primary" @click="onDeleteUsers">
              删除选中用户
            </el-button>
          </el-form-item>
        </el-form>
      </el-header>

      <el-main>
        <el-table
          :data="tableData"
          style="width: 100%; height: 90%"
          table-layout="auto"
          :heigth="800"
          highlight-current-row
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column fixed type="selection" width="50" />

          <el-table-column prop="name" label="姓名" min-width="90" />

          <el-table-column prop="sex" label="性别" min-width="60" />

          <el-table-column prop="phone" label="手机号" min-width="100" />

          <el-table-column prop="carNumber" label="车牌号" min-width="100" />

          <el-table-column prop="createTime" label="创建时间" min-width="200" />

          <el-table-column
            prop="createEmployeeName"
            label="创建者"
            min-width="90"
          />

          <el-table-column prop="updateTime" label="更新时间" min-width="200" />

          <el-table-column
            prop="updateEmployeeName"
            label="更新者"
            min-width="90"
          />

          <el-table-column fixed="right" label="操作" width="120">
            <template #default="{ row }">
              <el-button
                :icon="Edit"
                circle
                plain
                type="primary"
                @click="onEditUser(row)"
              ></el-button>

              <el-button
                :icon="Delete"
                circle
                plain
                type="danger"
                @click="onDeleteUser(row)"
              ></el-button>
            </template>
          </el-table-column>

          <template #empty>
            <el-empty :image-size="200" description="暂无数据" />
          </template>
        </el-table>

        <el-pagination
          v-model:current-page="formInline.currentPage"
          v-model:page-size="formInline.pageSize"
          :page-sizes="[5, 10, 20]"
          :page-counter="7"
          layout=" prev, pager, next, total, ->, jumper, sizes"
          background
          :total="pages.total"
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
          style="margin-top: 10px; justify-content: center"
        />
      </el-main>
    </el-container>

    <el-dialog
      v-model="dialogVisible"
      :title="formModel.id ? '编辑用户信息' : '添加用户'"
      width="40%"
    >
      <!-- 表单内容 -->
      <el-form
        :model="formModel"
        :rules="editRules"
        label-width="100px"
        style="padding: 0 30px"
        ref="dialogForm"
        :hide-required-asterisk="true"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="formModel.name"
            placeholder="请输入姓名"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-select v-model="formModel.sex" placeholder="请选择性别" clearable>
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="formModel.phone"
            placeholder="请输入手机号"
            clearable
          />
        </el-form-item>

        <el-form-item label="车牌号" prop="carNumber">
          <el-input
            v-model="formModel.carNumber"
            placeholder="请输入车牌号"
            clearable
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.root {
  height: 100%;
}

.list {
  height: 100%;

  .el-header {
    height: auto;
    margin: 10px 0;
    padding: 0;

    .el-form {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;

      .el-form-item {
        justify-content: end;
        align-items: center;
        margin: 0;
        margin-bottom: 10px;
      }
    }
  }

  .el-main {
    height: 100%;
    padding: 0;
  }
}

.el-dialog {
  .el-form {
    margin: 10px 40px 10px 0;
  }
}
</style>
